// pages/coll/coll.js
const db = wx.cloud.database()
var uid = wx.getStorageSync('openid');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartId: "",
    coll: [],
    default: true,
    reduce: false,
    promotion: false,
    available: false,
    pids: []
  },

  /* 页面最上方的选择，默认、降价、促销等 */
  click: function (options) {
    var name = options.currentTarget.dataset.name;
    // console.log(name)
    this.setData({
      default: false,
      reduce: false,
      promotion: false,
      available: false
    })
    if (name === "默认") {
      this.setData({
        default: true
      })
    } else if (name === "降价") {
      this.setData({
        reduce: true
      })
    } else if (name === "促销") {
      this.setData({
        promotion: true
      })
    } else if (name === "有货") {
      this.setData({
        available: true
      })
    } else {
      console("错误")
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    var pids = [];
    var coll = [];
    var cartId = "";
    var that = this;
    var i = 0;
    var j = 0;
    console.log(uid)
    await wx.cloud.callFunction({
      name: "getColl",
      data: {
        uid: wx.getStorageSync('openid')
      }
    }).then(res => {
      console.log(res)
      cartId = res.result.data[0]._id;
      res.result.data[0].pids.forEach(item => {
        pids.push(item)
      })
      // for(var x = res.result.data[0].pids.length; x > 0; x--){
      //   pids.push(res.result.data[0].pids[x])
      // }
      that.setData({
        cartId: cartId,
        pids
      })
      console.log(pids)
    })
    for (var x = 0; x < pids.length; x++) {
      await db.collection("product").where({
          _id: pids[x]
        })
        .get().then(res => {
          var {
            _id,
            pname,
            picUrl,
            price
          } = res.data[0];
          coll.unshift({
            _id,
            pname,
            picUrl,
            price,
            no: i,
          })
          i = i + 1;
          j = j + 1;
          console.log(coll)

        })
    }
    that.setData({
      coll
    })




    // })
  },

  delPro: function (options) {
    var id = options.currentTarget.dataset.id;
    console.log(id)
    var that = this;
    var i = 0;
    var no = options.currentTarget.dataset.no;;
    var coll = that.data.coll;
    coll.splice(no, 1);
    coll.forEach(item => {
      item.no = i;
      i = i + 1;
    })
    that.setData({
      coll
    })
    //删除云数据库中的数据

    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.cloud.callFunction({
      name: "delColl",
      data: {
        uid: wx.getStorageSync('openid'),
        pids: id
      }
    }).then(res => {
      setTimeout(function () {
        wx.hideLoading()
      }, 500)
    })
  },

})